import http from '@ohos.net.http';
// 后端服务地址：使用电脑局域网 IP + 端口；不要用设备上的 localhost
const BASE_URL = 'http://192.168.238.1:3001';

async function request(url, method = 'GET', data = {}) {
    const httpRequest = http.createHttp();
    const fullUrl = `${BASE_URL}${url}`;
    try {
        const response = await httpRequest.request(fullUrl, {
            method: method,
            connectTimeout: 10000,
            readTimeout: 10000,
            header: {
                'Content-Type': 'application/json'
            },
            extraData: method === 'POST' ? JSON.stringify(data) : {}
        });

        const code = response.responseCode;
        const raw = typeof response.result === 'string' ? response.result : (response.result ? response.result.toString() : '');

        if (code !== 200) {
            console.error('HTTP非200:', code, 'URL:', fullUrl, 'Raw:', raw);
            throw new Error(`HTTP ${code}`);
        }

        try {
            return JSON.parse(raw);
        } catch (e) {
            console.warn('JSON解析失败，返回原始字符串:', raw);
            return {};
        }
    } catch (err) {
        console.error('请求失败:', err, 'URL:', fullUrl);
        throw err;
    } finally {
        httpRequest.destroy();
    }
}
export default request;